﻿using System.Linq;
using Missbot.Common;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.AIModule.Base;
using Missbot.AIModule.OnlineStore;

namespace Missbot.AIModule.Gaming.Lottery
{
    [UsedImplicitly]
    public class LotteryMod : IAIModule
    {
        public override string Name => "抽奖功能";

        #region Svcs

        public LotterySvc LotterySvc { get; set; }
        public HonorSvc HonorSvc { get; set; }
        public WaiterSvc WaiterSvc { get; set; }

        #endregion

        [ModuleEnter(Command = "开箱子", Description = "花费100金币开一个箱子", DailyLimit = 3)]
        public bool DrawLottery(InboxSession session)
        {
            var osPerson = OSPersonDA.GetPerson(session.User.ID);
            if (osPerson.Golds < LotterySvc.LotteryFee)
            {
                session.SendBack($"你没有足够的金币开箱子({osPerson.Golds.CurencyFormat()}/{LotterySvc.LotteryFee.CurencyFormat()})");
                return false;
            }

            RandomLottery(session);

            return true;
        }

        private void RandomLottery(InboxSession session)
        {
            var lottery = LotterySvc.RandLottery();

            var absBonus = lottery.Bonus - LotterySvc.LotteryFee;
            LotteryRecordDA.Record(absBonus);

            var personRec = LotteryPersonDA.Get(session.User.ID);
            personRec.AddLottery(lottery.Name);
            personRec.Update();

            var golds = OSPersonDA.GoldConsume(session.User.ID, LotterySvc.LotteryFee - lottery.Bonus);

            var msg = $"{lottery.Print()}\n你当前持有金币：{golds.CurencyFormat()}";
            session.SendBack(msg);
        }

        [ModuleEnter(Command = "抽奖", Description = "抽取一件随机当月限定物品")]
        public bool LimitBonus(InboxSession session)
        {
            var cache = PersonCacheRecordDA.Get(session.User.ID, "抽奖");
            if (string.IsNullOrEmpty(cache.Value) || !int.TryParse(cache.Value, out var times) || times <= 0)
            {
                session.SendBack("你没有抽奖机会！");
                return false;
            }

            var items = HonorSvc.CurMonthLimitItems();
            var item = items.ToDictionary(p => p, p => p.Rate).RandRated();

            var buffer = new OutputBuffer(session);
            buffer.Add($"恭喜你抽到了 【{item.Name}】*1");
            buffer.Add($"    {item.Description} ");

            var record = ItemCollectionDA.Get(session.User.ID);
            var m = record.ItemIncome(item.Name);
            if (!string.IsNullOrEmpty(m))
            {
                buffer.Add(m);
            }

            buffer.Send();

            cache.Value = (times - 1).ToString();
            cache.Update();

            return true;
        }

        [ModuleEnter(Command = "十连抽", Description = "抽取十件随机当月限定物品")]
        public bool TenLimitBonus(InboxSession session)
        {
            var cache = PersonCacheRecordDA.Get(session.User.ID, "抽奖");
            if (string.IsNullOrEmpty(cache.Value) || !int.TryParse(cache.Value, out var times) || times < 10)
            {
                session.SendBack("你没有足够的抽奖机会！");
                return false;
            }

            var itemsRateDic = HonorSvc.CurMonthLimitItems().ToDictionary(p => p, p => p.Rate);
            var randItems = SafeDictionary<string, int>.Empty;
            for (var i = 0; i < 10; i++)
            {
                var randItem = itemsRateDic.RandRated();
                randItems[randItem.Name] += 1;
            }

            var itemColle = ItemCollectionDA.Get(session.User.ID);
            foreach (var (name, count) in randItems.Data)
            {
                itemColle.ItemIncome(name, count);
            }

            var msg = $"恭喜你抽到了 {randItems.Data.Select(p => $"【{p.Key}】*{p.Value}").JoinToString(",")} ！";
            session.SendBack(msg);

            cache.Value = (times - 10).ToString();
            cache.Update();

            return true;
        }

        [ModuleEnter(Command = "兑换抽奖机会", Description = "用金币兑换抽奖机会", DailyLimit = 3)]
        public bool GoldLimitBonus(InboxSession session)
        {
            var osPerson = OSPersonDA.GetPerson(session.User.ID);
            if (osPerson.Golds < 500)
            {
                session.SendBack($"你没有足够的金币兑换（{osPerson.Golds.CurencyFormat()}/{500.CurencyFormat()}）");
                return false;
            }

            if (!WaiterSvc.WaitForConfirm_Gold(session, 500))
            {
                session.SendBack("操作取消");
                return false;
            }

            osPerson.Golds -= 500;

            var cache = PersonCacheRecordDA.Get(session.User.ID, "抽奖");
            if (!int.TryParse(cache.Value, out var times))
            {
                times = 0;
            }

            times++;
            cache.Value = times.ToString();

            osPerson.Update();
            cache.Update();

            session.SendBack($"兑换成功，你现在共有{times}次抽奖机会，快使用 【抽奖】 命令试试看吧！");

            return true;
        }

        [ModuleEnter(Command = "今日开箱统计", Description = "获取今日开箱统计情况")]
        public bool LotteryAnalyzeToday(InboxSession session)
        {
            var todayRec = LotteryRecordDA.GetToday();
            session.SendBack(todayRec.Format());

            return true;
        }

        [ModuleEnter(Command = "昨日开箱统计", Description = "获取昨日开箱统计情况")]
        public bool LotteryAnalyzeYesterday(InboxSession session)
        {
            var yesterdayRec = LotteryRecordDA.GetYesterday();
            session.SendBack(yesterdayRec.Format());

            return true;
        }

        [ModuleEnter(Command = "我的开箱记录", Description = "获取自己的开箱统计")]
        public bool MyLotteryRecord(InboxSession session)
        {
            var rec = LotteryPersonDA.Get(session.User.ID);
            if (rec.LotteryDic.IsNullOrEmpty())
            {
                session.SendBack("你没有过任何开箱记录");
                return false;
            }

            session.SendBack(rec.Format());
            return true;
        }
    }
}